package com.shangdiao.sd_server.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shangdiao.sd_server.constant.Constant;
import com.shangdiao.sd_server.constant.ErrorCode;
import com.shangdiao.sd_server.pojo.ResponseMsg;
import com.shangdiao.sd_server.service.RedisService;
import com.shangdiao.sd_server.util.FastjsonUtil;
import com.shangdiao.sd_server.util.RequestRenderUtil;
import com.shangdiao.sd_server.util.RequestUtil;
import com.shangdiao.sd_server.util.SpringUtil;
import com.shangdiao.sd_server.util.StringUtil;

/**
 * 通行证验证过滤器
 * 
 * @author btshen
 */
public class PersonValidateFilter implements javax.servlet.Filter {

	protected Logger log = LoggerFactory.getLogger(getClass());
	
	private RedisService redisService;



	public void init(FilterConfig filterConfig) throws ServletException {
		redisService = SpringUtil.getBean(RedisService.class);
	}

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		
		ResponseMsg retMsg = null;
		
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rs = (HttpServletResponse) response;
		
		String uid = RequestUtil.get(rq, "uid");
		String token = RequestUtil.get(rq, "token");
		if(StringUtil.isBlank(uid) || StringUtil.isBlank(token)){
			retMsg = new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
			RequestRenderUtil.renderText(rs,FastjsonUtil.toJSONString(retMsg), "utf-8");
			return;
		}
		log.debug("URI:" + rq.getRequestURI());
		log.debug("url:" + rq.getRequestURL().toString());
		log.debug("uid:" + uid);
		log.debug("token:" + token);
		String token_in = redisService.get(Constant.PERSON_TOKEN_PRE + uid);
		if(token.equals(token_in)){
			chain.doFilter(request, response);
		}else{
			retMsg = new ResponseMsg("登录验证失败！", ErrorCode.INVALID_SID, null);
			RequestRenderUtil.renderText(rs,FastjsonUtil.toJSONString(retMsg), "utf-8");
			return;
		}
	}

	public void destroy() {

	}
}
